package ru.spbau.bytecode.projectobserver;

import java.io.File;
import java.io.IOException;

import ru.spbau.bytecode.graph.CompositeVertex;
import ru.spbau.bytecode.graph.Edge;
import ru.spbau.bytecode.graph.Graph;
import ru.spbau.bytecode.graph.GraphException;
import ru.spbau.bytecode.graph.Vertex;

public class CompositeObserver extends ProjectObserver {
	
	@Override
	public String getName() {
		return "Composite";
	}

	@Override
	protected void findDependencies(File[] classFiles, File projectDirectory,
			Graph graph, File currentDirectory) throws IOException {

		String currentDirectoryPath = currentDirectory.getAbsolutePath();

		String currentPackage = currentDirectoryPath.substring(
				projectDirectory.getAbsolutePath().length() + 1,
				currentDirectoryPath.length()).replace(File.separatorChar, '.');
		
		CompositeVertex v1 = new CompositeVertex(currentPackage);
		for (File f : classFiles) {
			String fileName = f.getName(); 
			// remove ".class" in the end of filename
			v1.addInnerVertex(new Vertex(fileName.substring(0, fileName.length() - 6)));
		}
		graph.addVertex(v1);
	}
	
	@Override
	public Graph buildGraph(File projectDirectory) throws GraphException {
		Graph graph = new ClassesObserver().buildGraph(projectDirectory);
		
		Graph compositeGraph = new Graph();
		try {
			processDirectory(projectDirectory, projectDirectory, compositeGraph);
		} catch (IOException e) {
			throw new GraphException(e);
		}
		
		for (Edge e: graph.getEdges()) {
			compositeGraph.addEdge(e);
		}
		return compositeGraph;
	}

}
